package com.hstc.servlet;

import com.hstc.common.Const;
import com.hstc.dao.DraftDAO;
import com.hstc.dao.StatusDAO;
import com.hstc.db.DbFactory;
import com.hstc.dto.MessageDTO;
import com.hstc.pojo.Draft;
import com.hstc.pojo.Status;
import com.hstc.pojo.Users;
import com.hstc.util.*;
import com.sun.mail.pop3.POP3Folder;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Connection;
import java.util.*;

/**
 * 邮件处理相关的Servlet
 */

@WebServlet(name = "MailServlet")
public class MailServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String url = request.getRequestURI();
        String basePath = "/jsp/";
        Users user = (Users) request.getSession().getAttribute(Const.USERNAME);
        if(url.toUpperCase().indexOf("SENDMAIL") != -1){
            //发送邮件
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2、创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            Map map = new HashMap();
            List<FileItem> list = null;
            String filename=null;
            try {
                list = upload.parseRequest(request);
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            for(FileItem item : list) {
                //如果fileitem中封装的是普通输入项的数据
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");
                    map.put(name, value);
                } else {//如果fileitem中封装的是上传文件

                    InputStream stream = item.getInputStream();//上传文件需要的文件流参数
                    filename = item.getName();   //上传文件需要的参数
                    if(filename == null || filename.trim().equals("")) {
                        continue;
                    }
                   UploadUtil.uploadFile(stream, Const.FILESAVEPATH, filename);   //调用工具类方法

                }
            }

            //发送邮件
            try{
                Session session = SMTPHelp.createSession();
                Message msg = new MimeMessage(session);
                InternetAddress from = new InternetAddress();
                from.setPersonal(user.getUsername());
                from.setAddress(SMTPHelp.getFrom(user.getUsername()));
                msg.setFrom(from);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String)map.get("toList")));
                msg.setSentDate(new Date());
                msg.setSubject((String)map.get("subject"));

                //抄送和暗送的处理
                String ccList = (String) map.get("ccList");
                String bccList = (String)map.get("bccList");

                msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse((String)map.get("ccList")));
                msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse((String)map.get("bccList")));
                MimeMultipart allMultipart = new MimeMultipart("mixed");
                //判断是否filename是否为空，添加附件的操作，
                if (filename != null && !filename.trim().equals("")) {

                    // TODO判空处理
                    MimeBodyPart attachPart1 = SMTPHelp.createAttachment(Const.FILESAVEPATH + filename);
                    //创建用于组合邮件正文和附件的MimeMultipart对象。
                    allMultipart.addBodyPart(attachPart1);
                }
                MimeBodyPart htmlBodyPart = SMTPHelp.createHtmlContent((String)map.get("content"));
                allMultipart.addBodyPart(htmlBodyPart);
                msg.setContent(allMultipart);
                msg.saveChanges();
                Transport transport = session.getTransport();
                transport.connect(Const.SERVER,user.getUsername(),user.getPwdHash());
                transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
                transport.close();
                request.setAttribute("msg", "发送成功");
                url = basePath + "index.jsp";
            }catch(MessagingException e ){
                e.printStackTrace();
                request.setAttribute("msg", "发送失败");
                url = basePath + "sendEmail.jsp";
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("msg", "发送失败");
                url = basePath + "sendEmail.jsp";
            }
            request.getRequestDispatcher(url).forward(request, response);

        }else if(url.toUpperCase().indexOf("MAILLIST") != -1) {
            //获取邮件列表
            Folder folder = POP3Help.getFolder(Const.SERVER, user.getUsername(), user.getPwdHash());
            request.getSession().setAttribute("folder", folder);
            POP3Folder inbox = (POP3Folder) folder;
            Message[] messages = new Message[0];
            List<MessageDTO> messageDTOList = new ArrayList<MessageDTO>();
            String from = null;
            String subject = null;
            Date sendDate  = null;
            Integer isNewCount = 0;
            try {
                messages = inbox.getMessages();
                StatusDAO statusDAO = new StatusDAO();
                for(int i = 0; i < messages.length; i++) {
                    MessageDTO messageDTO = new MessageDTO();
                    String uid = inbox.getUID((MimeMessage)messages[i]);
                    Status status = statusDAO.getStatus(new Status(user.getUsername(), uid), DbFactory.getConnection());
                    if(status != null) {
                        messageDTO.setNew(false);
                        messageDTO.setSeen(status.getSeen() == 0? false:true);
                    }else {
                        isNewCount++;
                        messageDTO.setNew(true);
                        messageDTO.setSeen(false);
                        statusDAO.addUid(new Status(user.getUsername(), uid), DbFactory.getConnection());
                    }
                    PraseMimeMsg pmm = new PraseMimeMsg((MimeMessage) messages[i]);
                    messageDTO.setFrom(pmm.getFrom());
                    messageDTO.setSubject(pmm.getSubject());
                    messageDTO.setSendData(pmm.getSentDate());
                    messageDTO.setMsgnum(i);
                    messageDTOList.add(messageDTO);
                }

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("messageDTOList", messageDTOList);
                jsonObject.put("isNewCount", isNewCount);
                response.getWriter().write(jsonObject.toString());

            } catch (MessagingException e) {
                e.printStackTrace();
            } catch(Exception e1){
                e1.printStackTrace();
            }

        }else if(url.toUpperCase().indexOf("SEARCHMAIL") != -1) {
            //阅读邮件
            String searchKey = request.getParameter("searchKey").trim();
            //获取邮件列表
            Folder folder = POP3Help.getFolder(Const.SERVER, user.getUsername(),user.getPwdHash() );
            Message[] messages = new Message[0];
            List<MessageDTO> messageDTOList = new ArrayList<MessageDTO>();
            SearchTerm searchItem = new SubjectTerm(searchKey);
            String from = null;
            String subject = null;
            Date sendDate  = null;
            try {
                messages = folder.search(searchItem);

                for(int i = 0; i < messages.length; i++) {
                    MessageDTO messageDTO = new MessageDTO();
                    from = messages[i].getFrom()[0].toString();
                    subject = messages[i].getSubject();
                    sendDate = messages[i].getSentDate();
                    messageDTO.setFrom(from);
                    messageDTO.setSubject(subject);
                    messageDTO.setSendData(DateTimeUtil.dateToStr(sendDate));
                    messageDTO.setMsgnum(i);
                    messageDTOList.add(messageDTO);
                }

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("messageDTOList", messageDTOList);
                response.getWriter().write(jsonObject.toString());

            } catch (MessagingException e) {
                e.printStackTrace();
            }


        }else if(url.toUpperCase().indexOf("KILLMAIL") != -1) {
            //删除邮件
            String  checkedIdArrayString = request.getParameter("checkedIdArray");
            String [] checkedIdArray = checkedIdArrayString.split(",");

            Integer [] checkedIdArray2 = new Integer[checkedIdArray.length];
            for(int i = 0; i < checkedIdArray.length; i++) {
                checkedIdArray2[i] = Integer.parseInt(checkedIdArray[i]);
            }
            //通过邮件的序号来删除邮件
            Folder folder = (Folder)request.getSession().getAttribute("folder");
            Message[] messages = new Message[0];
            try {
                messages = folder.getMessages();
                int line = 1;
                for(int i=0; i < checkedIdArray2.length; i++) {
                    //设置删除标记
                    line = checkedIdArray2[i];
                    messages[line].setFlag(Flags.Flag.DELETED, true);
                }
                folder.close(true);
                folder.getStore().close();
                response.getWriter().write("成功删除");
            } catch (MessagingException e) {
                e.printStackTrace();
                response.getWriter().write("删除失败");
            }
        }else if(url.toUpperCase().indexOf("REPLYMAIL") != -1) {
            //回复邮件

            Session session =  SMTPHelp.createSession();
            String to = request.getParameter("to");
            String subject = request.getParameter("subject");
            String content = request.getParameter("content");

            try{
                MimeMessage msg = new MimeMessage(session);
                InternetAddress from = new InternetAddress();
                from.setPersonal(user.getUsername());
                from.setAddress(SMTPHelp.getFrom(user.getUsername()));
                msg.setFrom(from);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                msg.setSentDate(new Date());
                msg.setSubject(subject);
                msg.setText(content);
                msg.saveChanges();
                Transport transport = session.getTransport();
                transport.connect(Const.SERVER,user.getUsername(),user.getPwdHash());
                transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
                transport.close();
                request.setAttribute("msg", "回复成功");
                url = basePath + "index.jsp";

            }catch(MessagingException e){
                request.setAttribute("msg", "回复失败");
                url = basePath + "index.jsp";

            }
            request.getRequestDispatcher(url).forward(request, response);
        }else if (url.toUpperCase().indexOf("FOWARDMAIL") != -1){
            //转发邮件

            String to = request.getParameter("toList");
            String subject = request.getParameter("subject");
            String content = request.getParameter("content");
            Integer msgnum = Integer.parseInt(request.getParameter("msgnum"));
            try{
                Folder folder = (Folder) request.getSession().getAttribute("folder");
                Message message= folder.getMessage(msgnum + 1);
                // 设置转发邮件信息头
                Session session = SMTPHelp.createSession();
                Message forward = new MimeMessage(session);
                InternetAddress from = new InternetAddress();
                from.setPersonal(user.getUsername());
                from.setAddress(SMTPHelp.getFrom(user.getUsername()));
                forward.setFrom(from);
                forward.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
                forward.setSubject(subject);
                // 设置转发邮件内容
                MimeBodyPart bodyPart = new MimeBodyPart();
                bodyPart.setContent(message.getContent(), "message/rfc822");
                Multipart multipart = new MimeMultipart();
                // MimeBodyPart htmlBodyPart = SMTPHelp.createHtmlContent(content);
                //multipart.addBodyPart(htmlBodyPart);
                //multipart.addBodyPart(bodyPart);
                forward.setContent(multipart);
                forward.saveChanges();
                Transport transport = session.getTransport();
                transport.connect(Const.SERVER, user.getUsername(), user.getPwdHash());
                transport.sendMessage(forward, forward.getRecipients(Message.RecipientType.TO));
                transport.close();
                request.setAttribute("msg", "转发成功");
                url = basePath + "index.jsp";
            }catch(MessagingException e){
                e.printStackTrace();
                request.setAttribute("msg", "转发失败");
                url = basePath + "forward.jsp";
            }catch(Exception e1) {
                e1.printStackTrace();
                request.setAttribute("msg", "转发失败");
                url = basePath + "forward.jsp";
            }
            request.getRequestDispatcher(url).forward(request, response);

        }

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
